package com.aos.util;

import com.aos.exception.BusinessException;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName ParamExceptionHandler
 * @Description:全局异常捕获
 * @Author wumingwang
 * @Date 2018/9/27 17:18
 * @Version 1.0
 */
@ControllerAdvice
@ResponseBody//必须添加，否则Spring会将返回值当作视图解析抛出异常
public class ParamExceptionHandler {
    @Autowired
    private HttpServletRequest request;

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object methodArgumentNotValidHandler(MethodArgumentNotValidException exception){
        //按需重新封装需要返回的错误信息
        StringBuilder sb = new StringBuilder();
        //解析原错误信息，封装后返回，此处返回非法的字段名称，错误信息
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            if(sb.length()>0){
                sb.append(",").append(error.getDefaultMessage());
            }else{
                sb.append(error.getDefaultMessage());
            }

        }
        return Result.error(sb.toString());
    }

    @ExceptionHandler(value = FeignException.class)
    public Object feignExceptionHandler(FeignException exception){
        //按需重新封装需要返回的错误信息
        String msg = exception.getMessage();
        String[] strs = msg.split("\"message\":\"");
        if(strs.length > 1){
            msg = strs[1].split("\"")[0];
        }
        return Result.error(msg);
    }

    @ExceptionHandler(value = BusinessException.class)
    public Object businessExceptionHandler(BusinessException exception){
        return Result.error(exception.getErrorMessage());
    }

}
